import Taro from '@tarojs/taro'

// 跳转导航
export const PageNavTo = (path: string) => {
  Taro.navigateTo({
    url: path
  })
}

// 环境判断

export const isWX = () =>{
  return process.env.TARO_ENV === 'weapp'
}


// toast 封装
export const showToast = (opts) => {
  if (typeof opts === 'string') {
    opts = {title: opts, icon: 'none'}
  } else {
    opts = Object.assign({icon: 'none'}, opts)
  }
  Taro.showToast(opts)
}

// 获取本地存储
export const getStorageSync = (key: string) => {
  try {
    return Taro.getStorageSync(key) || ''
  } catch (e) {
    showToast(e);
  }
}

// 设置本地存储
export const setStorageSync = (key: string, value: any) => {
  try {
    return Taro.setStorageSync(key, value)
  } catch (e) {
    showToast(e);
  }
}

// 移除本地存储
export const removeStorageSync = (key: string) => {
  try {
    return Taro.removeStorageSync(key)
  } catch (e) {
    showToast(e);
  }
}

// 存储token
export const setToken = (token: string) => {
  setStorageSync('userToken', token)
}

// 获取token
export const getToken = () => {
  return getStorageSync('userToken')
}

// 节流
export const throttle = (func: { apply: (arg0: any, arg1: IArguments) => void; }, delay: number) => {
  let timer: NodeJS.Timeout
  return function () {
    let context = this
    let args = arguments
    if (!timer) {
      timer = setTimeout(function () {
        clearTimeout(timer)
        func.apply(context, args)
      }, delay)
    }
  }
}
